#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/tcp.h> // 用于 TCP_KEEPIDLE, TCP_KEEPINTVL, TCP_KEEPCNT
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string.h>
#include <pthread.h>

#define PORT 8888
// #define IP "8.138.248.21"
#define IP "0.0.0.0"

// 客户端信息结构体
typedef struct
{
    int connfd;
    struct sockaddr_in addr;
    char client_name[1024];
} client_info_t;

void login(client_info_t *info)
{
    send(info->connfd, "请输入名字:", strlen("请输入名字:"), 0);

    // 接收客户端名字
    recv(info->connfd, info->client_name, sizeof(info->client_name), 0);

    size_t len = strcspn(info->client_name, "\n");
    if (len < strlen(info->client_name))
    { // 如果找到换行符
        info->client_name[len] = '\0';
    }

    printf("客户端[%s]连接成功!\n", info->client_name);

    char response[1024 * 2];
    sprintf(response, "用户[%s]接收成功!", info->client_name);
    send(info->connfd, response, strlen(response), 0);
}

void *server_recv(void *arg)
{
    client_info_t *info = (client_info_t *)arg;

    char client_ip[INET_ADDRSTRLEN];
    inet_ntop(AF_INET, &(info->addr.sin_addr), client_ip, INET_ADDRSTRLEN);

    printf("Client ip:%s, port:%d\n", client_ip, ntohs(info->addr.sin_port));

    login(info);

    while (1)
    {
        // 接收数据
        char buf[1024];
        ssize_t recv_res = recv(info->connfd, buf, sizeof(buf), 0);
        size_t len = strcspn(buf, "\n");
        if (len < strlen(buf))
        {
            buf[len] = '\0';
        }
        if (recv_res < 0)
        {
            perror("recv");
            continue;
        }
        if (recv_res == 0)
        {
            printf("客户端[%s]断开连接\n", info->client_name);
            close(info->connfd);
            break;
        }

        printf("客户端[%s]发送的数据：%s\n", info->client_name, buf);

        // 发送数据
        char buf1[1024] = "罚款50!";
        send(info->connfd, buf1, strlen(buf1), 0);
        memset(buf, 0, sizeof(buf));
    }
    free(info);
    return NULL;
}

int main()
{
    int socketfd = socket(AF_INET, SOCK_STREAM, 0); // 0 表示使用默认协议

    // 创建地址结构体
    struct sockaddr_in addr;
    memset(&addr, 0, sizeof(addr));

    addr.sin_family = AF_INET;
    addr.sin_port = htons(PORT);
    addr.sin_addr.s_addr = inet_addr(IP);

    int optval = 1;
    setsockopt(socketfd, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval));
    // 绑定
    bind(socketfd, (struct sockaddr *)&addr, sizeof(addr));

    // 监听
    listen(socketfd, 10); // 10 表示最大连接数
    printf("监听中...\n");

    while (1)
    {
        printf("waiting....\n");

        struct sockaddr_in client_addr;
        memset(&client_addr, 0, sizeof(client_addr));

        // 等待客户端连接
        int ClientAddr_len = sizeof(client_addr);
        int connfd = accept(socketfd, (struct sockaddr *)&client_addr, &ClientAddr_len);

        // TCP心跳检测
        int keepIdle = 60;     // 连接空闲n秒后开始发送Keepalive探测包
        int keepInterval = 10; // 每次探测包之间的间隔时间为n秒
        int keepCount = 10;    // 最多发送n次探测包
        setsockopt(connfd, SOL_TCP, TCP_KEEPIDLE, (void *)&keepIdle, sizeof(keepIdle));
        setsockopt(connfd, SOL_TCP, TCP_KEEPINTVL, (void *)&keepInterval, sizeof(keepInterval));
        setsockopt(connfd, SOL_TCP, TCP_KEEPCNT, (void *)&keepCount, sizeof(keepCount));

        if (connfd < 0)
        {
            perror("accept");
            continue;
        }
        client_info_t *info = (client_info_t *)malloc(sizeof(client_info_t));
        memset(info, 0, sizeof(client_info_t));
        info->connfd = connfd;
        info->addr = client_addr;

        pthread_t tid;
        pthread_create(&tid, NULL, server_recv, info);
        pthread_detach(tid);
    }
    close(socketfd);
    close(socketfd);
    return 0;
}
